<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="Userid" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入Userid" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="分组" prop="groupCode">
        <el-select v-model="queryParams.groupCode" placeholder="请选择分组" clearable size="small">
          <el-option v-for="dict in groupOptions" :key="dict.groupCode" :label="dict.groupName"
            :value="dict.groupCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="邀请方" prop="recommendPhone">
        <el-input v-model="queryParams.recommendPhone" placeholder="请输入邀请方" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="邀请码" prop="inviteCode">
        <el-input v-model="queryParams.inviteCode" placeholder="请输入邀请码" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" :disabled="multiple" @click="handleUpdate"
          v-hasPermi="['bizsys:agent:edit']">修改分组</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" @click="handleUpload" v-hasPermi="['bizsys:agent:edit']">导入修改分组
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="AgentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="Userid" align="center" prop="userId" show-overflow-tooltip />
      <el-table-column label="手机号" align="center" prop="phone" width="110" />
      <el-table-column label="分组" align="center" prop="groupCode" width="110" :formatter="groupNameFormatter" />
      <el-table-column label="邀请方" align="center" prop="recommendPhone" width="110" />
      <el-table-column label="累计邀请人数" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleInviteList(scope.row)" v-hasPermi="['bizsys:agent:edit']">
            {{scope.row.invitedCount}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="累计获得佣金(₦)" align="center" width="110" prop="awardAmount" />
      <el-table-column label="邀请码" align="center" prop="inviteCode" />
      <el-table-column label="邀请链接" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          {{ scope.row.inviteLink }}
          <el-button v-show="scope.row.inviteLink" size="mini" type="text" @click="handleCopy(scope.row)">
              复制
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="inviteCodeStatus" :formatter="inviteCodeStatusFormatter" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text"
            @click="handleUpdateStatus(scope.row)" v-hasPermi="['bizsys:agent:edit']">
              {{ scope.row.inviteCodeStatus === '1'?'冻结':'解冻' }}
          </el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['bizsys:agent:edit']">修改分组
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 下级代理人 -->
    <el-dialog :title="invite.title" :visible.sync="invite.open" width="1000px" append-to-body>
      <div class="app-container">
        <el-form :model="invite.queryParams" ref="queryFormInvite" :inline="true" v-show="invite.showSearch"
          label-width="100px">
          <el-form-item label="Userid" prop="userId">
            <el-input v-model="invite.queryParams.userId" placeholder="Userid" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="invite.queryParams.phone" placeholder="手机号" clearable size="small"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="分组" prop="groupCode">
            <el-select v-model="invite.queryParams.groupCode" placeholder="请选择分组" clearable size="small">
              <el-option v-for="dict in groupOptions" :key="dict.groupCode" :label="dict.groupName"
                :value="dict.groupCode" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryInvite">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQueryInvite">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="invite.showSearch" @queryTable="getInviteList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="invite.invoteList">
          <el-table-column label="Userid" align="center" prop="userId" width="280" />
          <el-table-column label="手机号" align="center" prop="phone" />
          <el-table-column label="邀请方" align="center" prop="recommendPhone" />
          <el-table-column label="分组" align="center" prop="groupCode" :formatter="groupNameFormatter" />
          <el-table-column label="累计邀请人数" align="center" prop="invitedCount" />
          <el-table-column label="累计获得佣金(₦)" align="center" prop="awardAmount" />
        </el-table>

        <pagination v-show="invite.total>0" :total="invite.total" :page.sync="invite.queryParams.pageNum"
          :limit.sync="invite.queryParams.pageSize" @pagination="getInviteList" />
      </div>
    </el-dialog>

    <!-- 上传excel -->
    <el-dialog :visible.sync="upload.open" width="500px" append-to-body>
      请上传Excel表格
      <el-upload class="upload-demo" :on-success="handleUploadSuccess" :on-error="handleUploadError" :action="upload.url" :headers="upload.headers" multiple :limit="1"
        :on-exceed="onExceed">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传.xlsx文件，且不超过500kb</div>
        <div slot="tip" class="el-upload__tip">excel列头:[userId]-[groupCode]</div>
      </el-upload>
    </el-dialog>

    <!--  选择分组 -->
    <el-dialog center :title="selectGroup.title" :visible.sync="selectGroup.open" width="350px" append-to-body>
      <el-form :rules="selectGroup.rules" :model="selectGroup.params" ref="formSelectGroup" :inline="true"
        label-width="80px">
        <el-form-item label="选择分组" prop="groupCode">
          <el-select v-model="selectGroup.params.groupCode" placeholder="请选择分组" clearable size="small">
            <el-option v-for="dict in groupOptions" :key="dict.groupCode" :label="dict.groupName"
              :value="dict.groupCode" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitSelectGroup">确 定</el-button>
        <el-button @click="cancelSelectGroup">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listAgent,
    updateGroup,
    importFile,
    freezeInviteState,
  } from "@/api/bizsys/award_agent";
  import {
    listGroup,
  } from "@/api/bizsys/award_group";

  export default {
    name: "Agent",
    components: {},
    data() {
      return {
        selectGroup: {
          title: '请选择分组',
          open: false,
          params: {
            userIds: [],
            groupCode: "",
            groupId: "99999"
          },
          // 表单校验
          rules: {
            groupCode: [{
              required: true,
              message: "分组不能为空",
              trigger: "blur"
            }],
          }
        },
        upload: {
          headers: {},
          fileList: [],
          url: '',
          open: false,
        },
        invite: {
          title: '代理人下级',
          invoteList: [],
          total: 0,
          open: false,
          queryParams: {
            pageNum: 1,
            pageSize: 10,
          },
          showSearch: true,
        },
        //分组选择列表
        groupOptions: [],
        // 遮罩层
        loading: true,
        // 选中数组
        selectList: [],
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 奖励活动表格数据
        AgentList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          actName: null,
          actType: null,
          distributionRatioId: null,
          startTime: null,
          endTime: null,
          state: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          createTime: [{
            required: true,
            message: "创建时间不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    created() {
      this.getList();
      this.getGroupList();
      let obj = importFile();
      this.upload.url = obj.url;
      this.upload.headers = obj.headers;
    },
    methods: {
      handleUploadSuccess(response){
        if(response.code!=200){
          this.msgError(response.msg)
          return
        }
        this.msgSuccess('上传成功')
        this.getList()
      },
      handleUploadError(){
        this.msgError('上传异常')
      },
      //代理人状态
      inviteCodeStatusFormatter(row, column) {
        return row.inviteCodeStatus == '1' ? '正常' : row.inviteCodeStatus == '0' ? '冻结' : '注销';
      },
      // 分组字典翻译
      groupNameFormatter(row, column) {
        let datas = this.groupOptions;
        let value = row.groupCode;
        var actions = [];
        Object.keys(datas).some((key) => {
          if (datas[key].groupCode == ('' + value)) {
            actions.push(datas[key].groupName);
            return true;
          }
        })
        return actions.join('');
      },
      /**  查询分组选项 */
      getGroupList() {
        listGroup().then(response => {
          this.groupOptions = response.rows;
        });
      },
      /** 查询代理人列表 */
      getList() {
        this.loading = true;
        listAgent(this.queryParams).then(response => {
          this.AgentList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询下级代理人列表*/
      getInviteList() {
        this.loading = true;
        listAgent(this.invite.queryParams).then(response => {
          this.invite.invoteList = response.rows;
          this.invite.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮
      cancelSelectGroup() {
        this.selectGroup.open = false;
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          actName: null,
          actType: null,
          distributionRatioId: null,
          startTime: null,
          endTime: null,
          state: null,
          remark: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 打开下级代理人操作 */
      handleInviteList(row) {
        if (row.invitedCount == 0) return;
        this.invite.open = true;
        this.invite.queryParams.recommendCode = row.inviteCode;
        this.resetQueryInvite()
        this.getInviteList()
      },
      /** 下级代理人搜索按钮操作 */
      handleQueryInvite() {
        this.invite.queryParams.pageNum = 1
        this.getInviteList()
      },
      /** 复制连接 */
      handleCopy(row) {
        let inviteLink =  row.inviteLink;
        var input = document.createElement('input'); //创建一个隐藏input（重要！）
        input.value = inviteLink; //拼接多个赋值
        document.body.appendChild(input);
        input.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        input.className = 'oInput';
        input.style.display = 'none';
        this.$message.success("复制成功！")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      //冻结
      handleUpdateStatus(row) {
        let _this = this;
        let msg = ""
        let params = {}
        if(row.inviteCodeStatus==='1'){
          msg='冻结'
          params.inviteCodeStatus = '0'
        }else{
          msg='解冻'
          params.inviteCodeStatus = '1'
        }
        this.$confirm('是否确定冻结代理人', "", {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }).then(function() {
          return freezeInviteState(row.userId,params);
        }).then(() => {
          _this.getList();
        })
      },
      // 确定分组选择
      handleSubmitSelectGroup() {
        this.$refs["formSelectGroup"].validate(valid => {
          if (valid) {
            return updateGroup(this.selectGroup.params).then(response => {
              this.selectGroup.open = false;
              this.getList()
            });;
          }
        });
      },
      //修改分组
      handleUpdate(row) {
        /** 清空选项 */
        this.selectGroup.params.groupCode = null;
        //封装参数
        let userIds = row.userId || this.selectList.map(obj => obj.userId);
        userIds = userIds instanceof Array ? userIds : new Array(userIds);
        this.selectGroup.params.userIds = userIds
        this.selectGroup.open = true
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selectList = selection
        this.multiple = !selection.length
      },
      handleUpload() {
        this.upload.open = true;
      },
      onExceed() {
        this.$message.error(`只允许上传单个文件`);
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 下级代理人重置按钮操作 */
      resetQueryInvite() {
        this.resetForm("queryFormInvite");
        this.handleQueryInvite();
      },
    }
  };
</script>
